package cn.biplam.back.services.page;

import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import cn.biplam.common.interfaces.PageExchangeServer;
import cn.biplam.common.tools.TOOLS;
import cn.biplam.common.wrapper.ErrorMessage;
import cn.biplam.common.wrapper.KvMap;
import cn.biplam.common.wrapper.sqlresult.SqlResult;

/**
 * 页面交换请求接口实现类
 * @author WangSong 2009-9-23下午04:59:41
 * @version 1.0
 */
public class PageExchangeServerImpl extends UnicastRemoteObject implements PageExchangeServer{

	private static final long serialVersionUID = 5617723870006198419L;
	private Lock mLock=new ReentrantLock();
	private int iCount=0;
	private static KvMap<String, String> map;
	
	/**
	 * 构造方法
	 * @throws RemoteException
	 */
	public PageExchangeServerImpl() throws RemoteException {
		iCount++;
		map=new KvMap<String, String>();
	}
	
	/**
	 * 请求页面
	 * @param request
	 * @param response
	 * @param pageName 页面名称
	 * @return 请求的页面
	 * @throws RemoteException
	 * @throws ErrorMessage
	 */
	public String get(String pageName) throws RemoteException, ErrorMessage {
		addCount();
		try{
			return getContent(pageName);
		}catch(Exception e){
			throw new ErrorMessage(e);
		}finally{
			reduceCount();
		}
	}
	
	/**
	 * 取页面内容
	 * @param pageId
	 * @return
	 * @throws ErrorMessage
	 */
	private String getContent(String pageName) throws ErrorMessage{
		String pageClass=map.getByKey(pageName);
		/**根据action查询配置表中操作类*/
		return pageClass==null?getClassByPageId(pageName):pageClass;
	}
	
	/**
	 * 根据行为编码来查询实现类
	 * @param actionId 行为编码id
	 * @return 实现类
	 * @throws ErrorMessage 
	 */
	private String getClassByPageId(String pageId) throws ErrorMessage{
		SqlResult sr = new PageServiceOpt().getById(pageId);
		if(TOOLS.exist(sr)){
			map.put(pageId, sr.get(0,"s_class_path"));
			return sr.get(0,"s_class_path");
		}else{
			throw new ErrorMessage("\n\tPageExchangeServerImpl error,page is not found:"+pageId);
		}
	}

	/**服务监控用*/
	public int getCount() throws RemoteException {
		return this.iCount;
	}

	private synchronized void addCount() {
		this.iCount++;
	}

	private synchronized void reduceCount() {
		this.iCount--;
	}

	public void lock() throws RemoteException {
		mLock.lock();
	}

	public boolean trylock() throws RemoteException {
		return mLock.tryLock();
	}

	public void unlock() {
		mLock.unlock();
	}
	
}
